<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseEnum;
use App\Http\Requests\CreateOrderRequest;
use App\Http\Requests\GoPayRequest;
use App\Models\Address;
use App\Models\Goods;
use App\Models\Orders;
use App\Models\System;
use App\Models\Users;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Arr;

class OrderController extends BaseController
{
    /**
     * @return
     * 提交订单页面
     */
    public function store(){
        $address = Address::where('user_id' , Arr::get(session('loginUser') , 'id'))->where('is_default' , 1)->first();

        return view('order/submit' , ['address' => $address]);
    }


    /**
     * @param OrderRequest $request
     * @return \Illuminate\Http\JsonResponse
     * 创建订单
     */
    public function subOrder(CreateOrderRequest $request)
    {
        $credentials = request(['address_id', 'goods_id', 'num']);

        $sessionInfo = session('loginUser');

        try {

            $goodsInfo = Goods::where('id', Arr::get($credentials , 'goods_id'))->where('is_show' , 1)->first();

            if(empty($goodsInfo)){
                return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
            }

            $addressInfo = Address::where('user_id', Arr::get($sessionInfo , 'id'))->where('id', Arr::get($credentials , 'address_id'))->first();

            $userInfo = Users::where('id', Arr::get($sessionInfo , 'id'))->first();

            if (empty($addressInfo)) {
                return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
            }

            if (empty($userInfo)) {
                return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED);
            }
            //订单号
            $order['order_sn'] = $this->orderSn();
            //下单用户
            $order['user_id'] = $userInfo->id;
            //所属上级的用户id
            $order['parent_user_id'] = $userInfo->parent_user_id;
            //商品ID
            $order['goods_id'] = $goodsInfo->id;
            //商品名称
            $order['goods_name'] = $goodsInfo->goods_name;
            //商品数量
            $order['goods_num'] = Arr::get($credentials , 'num');
            //商品单价
            $order['goods_prices'] = $goodsInfo->goods_prices;
            //商品封面
            $order['goods_cover'] = $goodsInfo->goods_cover;
            //实付款
            $order['prices'] = $credentials['num'] * $goodsInfo->goods_prices;
            //订单总价
            $order['total_price'] = $credentials['num'] * $goodsInfo->goods_prices;
            //收货人姓名
            $order['user_name'] = $addressInfo->name;
            //收货人手机号
            $order['user_mobile'] = $addressInfo->mobile;
            //收货地址
            $order['shipping_address'] = $addressInfo->area . ' ' . $addressInfo->address;
            //订单状态
            $order['status'] = 1;
            //用户open_idq
            $order['open_id'] = $userInfo->open_id;
            //域名
            $order['host'] = $request->getHost();

            $result = $this->unifiedorder($order);

            if (empty($result)) {
                return $this->fail(ResponseEnum::SERVICE_WECHAT_PAY_ERROR);
            }

            $order['prepay_id'] = substr(Arr::get($result , 'package') , 10);

            if(Orders::create($order)){
                return $this->success($result);
            }

            return $this->fail(ResponseEnum::SERVICE_WECHAT_PAY_ERROR);

        } catch (\Exception $error) {
            return $this->fail();
        }
    }


    /**
     * @param GoPayRequest $request
     * 我的订单去支付
     */
    public function goPay(GoPayRequest $request){
        $orderInfo = Orders::where('order_sn', $request->post('order_sn'))->where('user_id', Arr::get(session('loginUser') , 'id'))->where('status', 1)->first();

        if($orderInfo) {
            //订单已过期
            if ($orderInfo->created_at->timestamp + 7000 < time()) {
                //订单已过期
                $orderInfo->status = 5;

                $orderInfo->status_msg = '订单未在规定时间支付,订单已过期';

                $orderInfo->save();

                return $this->fail(ResponseEnum::USER_ORDER_OVERTIME);
            }

            //订单号
            $order['order_sn'] = $orderInfo->order_sn;
            //商品名称
            $order['goods_name'] = $orderInfo->goods_name;
            //实付款
            $order['goods_prices'] = $orderInfo->prices;
            //用户open_id
            $order['open_id'] = Users::where('id' , Arr::get(session('loginUser') , 'id'))->value('open_id');
            //
            $order['host'] = $request->getHost();
            //支付秘钥
            $order['prepay_id'] = $orderInfo->prepay_id;;

            $result = $this->unifiedorder($order);

            if(is_array($result)){
                return $this->success($result);
            }
        }
        return $this->fail(ResponseEnum::HTTP_ERROR);
    }





    /**
     * @param $orderSn
     * @return \Illuminate\Http\JsonResponse
     * 取消订单
     */
    public function cancelOrder($orderSn){
        $order = Orders::where('order_sn' , $orderSn)->where('user_id' , Arr::get(session('loginUser') , 'id'))->where('status' , 1)->first();

        if(!empty($order)){
            $order->status = 5;

            if($order->save()){
                return $this->success();
            }
        }
        return $this->fail();
    }


    /**
     * @param $orderSn
     * @return \Illuminate\Http\JsonResponse
     * 确认收货
     */
    public function confirmOrder($orderSn){
        $order = Orders::where('order_sn' , $orderSn)->where('user_id' , Arr::get(session('loginUser') , 'id'))->where('status' , 3)->first();
        if(!empty($order)){
            $order->status = 4;

            if($order->save()){
                return $this->success();
            }
        }
        return $this->fail();
    }


    /**
     * @param array $order
     * 统一下单接口
     */
    public function unifiedorder($order = [])
    {


        $config = [
            // 必要配置
            'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID'),

            'mch_id' => '1607422347',

            'key' => env('WECHAT_APP_PAY_SECRET'),   // API 密钥

            'notify_url' => 'http://' . $order['host'] . '/wechat/payCallback',     // 你也可以在下单时单独设置来想覆盖它
        ];

        $payment = Factory::payment($config);


        if(isset($order['prepay_id']) && !empty($order['prepay_id'])){
            $jssdk = $payment->jssdk;

            $json = $jssdk->bridgeConfig(Arr::get($order , 'prepay_id'));

            return json_decode($json , true);
        }

        $result = $payment->order->unify([

            'body' => Arr::get($order , 'goods_name'),

            'out_trade_no' => Arr::get($order , 'order_sn'),

            'total_fee' => Arr::get($order , 'prices') * 100,

            'notify_url' => Arr::get($config , 'notify_url'),

            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型

            'sandbox' => true, //沙箱支付

            'attach' => json_encode(['user_id' => Arr::get($order , 'user_id') , 'parent_user_id' => Arr::get($order , 'parent_user_id')]),

            'openid' => Arr::get($order , 'open_id'),
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

            $jssdk = $payment->jssdk;

            $json = $jssdk->bridgeConfig(Arr::get($result , 'prepay_id'));

            return json_decode($json , true);
        }

        return [];
    }


    /**
     * @description: 生成唯一订单号
     * @param {type}
     * @return:
     */
    static public function orderSn()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AB', 'CD', 'EF', 'GH', 'IJ', 'KL', 'MN', 'OP', 'QR', 'ST', 'UV', 'XY', 'ZA');

        return $yCode[intval(date('Y')) - 2021] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }
}
